﻿using Dapper;
using MediatR;
using MySql.Data.MySqlClient;

using Newtonsoft.Json;
using SCM.API.Read.Application.Command;
using SCM.API.Read.Application.Command.Purchase;
using SCM.Domain;
using SCM.ErrorCode;
using SCM.Infrastructure.Interface;
using System.Data;
using System.Text;

namespace SCM.API.Read.Application.Handler.Purchase
{
    public class GetPurchaseHandler : IRequestHandler<GetPurchaseCommand, APIResult<PurchaseManagementModel>>
    {
       ILogger<GetPurchaseHandler> logger;
        IDatabaseContext db;

        public GetPurchaseHandler(ILogger<GetPurchaseHandler> logger, IDatabaseContext db)
        {
            this.logger = logger;
            this.db = db;
        }

        public async Task<APIResult<PurchaseManagementModel>> Handle(GetPurchaseCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new APIPaging<PurchaseManagementModel>();

                var countSql = new StringBuilder();
                var sqlBuilder = new StringBuilder();

                sqlBuilder.Append(@"SELECT 
                                        id,
                                        ProductName,
                                        purchaseId,
                                        productId,
                                        productSpecs,
                                        unitId,
                                        price,        
                                        num,
                                        total,
                                        OrderType,
                                        vendorId,
                                        vendorName,
                                        ContactPerson,
                                        Phone,
                                        Description,
                                        state,
                                        recorded,
                                        refund,
                                        madeName,
                                        madeTime,
                                        createTime,
                                        updateName,
                                        createName,
                                        isDel,
                                        LocationId,
                                        Bacth
                                FROM PurchaseManagementModel WHERE IsDel=0 ");

                countSql.Append("SELECT COUNT(id) FROM PurchaseManagementModel WHERE isDel=0 ");

                var parameters = new DynamicParameters();

                if (!string.IsNullOrEmpty(request.PurchaseId))
                {
                    sqlBuilder.Append("AND PurchaseId = @PurchaseId ");
                    parameters.Add("PurchaseId", request.PurchaseId);
                    countSql.Append("AND PurchaseId = @PurchaseId ");
                }
                if (!string.IsNullOrEmpty(request.ProductName))
                {
                    sqlBuilder.Append(" AND ProductName LIKE @ProductName ");
                    parameters.Add("ProductName", $"%{request.ProductName}%");
                    countSql.Append(" AND ProductName LIKE @ProductName ");
                }

                if (request.ProductId!=null)
                {
                    sqlBuilder.Append("AND ProductId = @ProductId ");
                    parameters.Add("ProductId", request.ProductId);
                    countSql.Append("AND ProductId = @ProductId ");
                }
                if (request.State != null)
                {
                    sqlBuilder.Append("AND State = @State ");
                    parameters.Add("State", request.State);
                    countSql.Append("AND State = @State ");
                }
                sqlBuilder.Append("ORDER BY CreateTime DESC ");
                sqlBuilder.Append("LIMIT @PageSize OFFSET @Offset ");
                parameters.Add("PageSize", request.PageSize);
                parameters.Add("Offset", (request.PageIndex - 1) * request.PageSize);

               

                var data = await db.DapperConnection.QueryAsync<PurchaseManagementModel>(sqlBuilder.ToString(), parameters);
                var total = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);

                result.Msg = "显示成功";
                result.Code = APIEnum.Success;
                result.items = data.ToList();
                result.totalCount = total;
                result.totalPage = (int)Math.Ceiling((double)total / request.PageSize);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message, "查询采购信息失败");
                throw;
            }
           
        }
    }
}
